package net.bcxuexi.socket.stream.inhandle;

import net.bcxuexi.config.Config;
import net.bcxuexi.exception.MyException;
import net.bcxuexi.socket.SocketManager;
import net.bcxuexi.socket.model.SocketModel;
import net.bcxuexi.socket.stream.StreamData;
import net.bcxuexi.socket.stream.outwrap.OutputDataWrap;
import net.bcxuexi.tools.MyLog;

public class DataInputStreamHandler extends AbstractInputStreamHandler{

	@Override
	public void handle() {
		StreamData streamData = null;// 待处理数据

		if (streamData == null) {
			try {
				streamData = take();// 从阻塞队列中取数据，可能会被阻塞
			} catch (InterruptedException e) {
				// 没有取到数据
				return;
			}
		}

		if (streamData == null) {
			MyLog.info("DataInputStreamHandler队列为空，休息！");
			return;
		}
		// 数据处理
		process(streamData);
		try {
			sleep(80);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解析协议
	 * @param streamData
	 */
	public void process(StreamData streamData) {
		if(Config.debug){
			String dmsg = new String(streamData.data,0,streamData.total);
			MyLog.info("接收到服务器data数据："+dmsg);
		}
		
		/*
		 * 解析协议
		 * 第0个字节为2:代表数据通信
		 * 第1到8个字节:代表proxy socket的connId
		 * 第9到20个字节:代表内网服务器的4位ip 192168001155
		 * 第21到25个字节:代表内网服务器的端口 如:61235,08080
		 */
		byte[] msg = streamData.data;
		String proxySocketConnId = new String(msg,1,8);
		String innerIp = Integer.valueOf(new String(msg,9,3))+"."+Integer.valueOf(new String(msg,12,3))+"."+Integer.valueOf(new String(msg,15,3))+"."+Integer.valueOf(new String(msg,18,3));
		int innerPort = Integer.valueOf(new String(msg,21,5));
		//找到内网指定服务连接socket(如果是http协议以后要单独处理),没有则新建
		SocketModel innerSocketModel = SocketManager.getInstance().createInnerSocket(proxySocketConnId, innerIp, innerPort);
		
		
		//数据发送到内网指定服务器
		if(innerSocketModel!=null){
			MyLog.info("proxyConnId:"+proxySocketConnId+"对应的innerSocket connId为："+innerSocketModel.getConnId());
			
			byte[] data = new byte[streamData.total-26];
			for(int i=0;i<data.length;i++){
				data[i] = msg[26+i];
			}
			if(Config.debug){
				String dmsg = new String(data,0,data.length);
				MyLog.info("data数据去掉头部消息后："+dmsg);
			}
			StreamData innerStreamData = new StreamData();
			innerStreamData.setData(data);
			innerStreamData.setSocketModel(innerSocketModel);
			innerStreamData.setTotal(data.length);
			try {
				innerSocketModel.getWriteStream().addData(innerStreamData);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
